package com.trkj.base.newwork;

import android.content.Context;
import android.os.AsyncTask;

import com.trkj.base.Constants;
import com.trkj.base.OnResponseResultListener;

/**
 * 从远程服务器获取数据，不出现等待的进度条对话框
 * Created by LiZanhong on 2015/06/20.
 */
public class WaitingDataFromRemote extends AsyncTask<String, Integer, String>{
    private Context context;
    private OnResponseResultListener responseResultListener;
    private HttpRequest httpRequest;

    public HttpRequest getHttpRequest() {
        return httpRequest;
    }

    public WaitingDataFromRemote(Context context) {
        this.context = context;
        httpRequest = new HttpRequest();
    }

    public WaitingDataFromRemote(Context context,
                                 OnResponseResultListener responseResultListener) {
        this(context);
        this.responseResultListener = responseResultListener;
    }

    public Context getContext() {
        return context;
    }

    public void setResponseResultListener(
            OnResponseResultListener responseResultListener) {
        this.responseResultListener = responseResultListener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(responseResultListener == null){
            throw new NullPointerException("没有定义用于处理结果的监听器");
        }
        responseResultListener.onResponseResult(s);
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        httpRequest.setCancelled(true);
    }

    @Override
    protected String doInBackground(String... params) {
        //判断网络
        if(!NewWorkUtils.isNetworkAvailable(context)){
            return Constants.FAILURE_JSON;
        }

        String url = params[0];
        String param = null;
        if(params.length > 1){
            param = params[1];
        }
        String str = httpRequest.sendGet(url, param);

        return str;
    }

}
